document.addEventListener('DOMContentLoaded', function() {
    const attackBtn = document.getElementById('attack-btn');
    const battleMessages = document.getElementById('battle-messages');
    const monsterHpFill = document.getElementById('monster-hp-fill');
    const monsterHpText = document.getElementById('monster-hp');

    let isBattleActive = true;

    attackBtn.addEventListener('click', async function() {
        if (!isBattleActive) return;
        
        try {
            const response = await fetch(`/game/battle/${floorId}/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    action: 'attack'
                })
            });

            const data = await response.json();
            
            // 更新战斗界面
            updateBattleUI(data);
            
            // 检查战斗结果
            if (data.battle_result) {
                handleBattleEnd(data.battle_result);
            }
        } catch (error) {
            console.error('战斗出错:', error);
        }
    });

    function updateBattleUI(data) {
        // 更新怪物血量
        const monsterHpPercentage = (data.battle_state.monster_hp / monsterMaxHp) * 100;
        monsterHpFill.style.width = `${monsterHpPercentage}%`;
        monsterHpText.textContent = `HP: ${data.battle_state.monster_hp}/${monsterMaxHp}`;

        // 更新玩家血量
        const playerHpPercentage = (data.battle_state.player_hp / playerMaxHp) * 100;
        document.querySelector('.hp-fill').style.width = `${playerHpPercentage}%`;
        document.querySelector('.character-stats .hp-bar span').textContent = 
            `HP: ${data.battle_state.player_hp}/${playerMaxHp}`;

        // 添加战斗消息
        addBattleMessage(`你对怪物造成了${data.player_attack.damage}点伤害！`);
        if (data.monster_attack) {
            addBattleMessage(`怪物对你造成了${data.monster_attack.damage}点伤害！`);
        }
    }

    function handleBattleEnd(result) {
        isBattleActive = false;
        if (result === 'victory') {
            addBattleMessage('战斗胜利！');
            setTimeout(() => {
                window.location.href = `/game/tower/`;
            }, 2000);
        } else {
            addBattleMessage('战斗失败...');
            setTimeout(() => {
                window.location.href = `/game/game-over/`;
            }, 2000);
        }
    }

    function addBattleMessage(message) {
        const li = document.createElement('li');
        li.textContent = message;
        battleMessages.appendChild(li);
        battleMessages.scrollTop = battleMessages.scrollHeight;
    }

    function getCookie(name) {
        // 获取CSRF Token的辅助函数
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}); 